package com.example.mqtt.paho.mqtt.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @author long
 * mqtt配置
 */
@Configuration
public class MqttConfig {

    private static final Logger logger = LoggerFactory.getLogger(MqttConfig.class);

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.hostUrl}")
    private String hostUrl;

    @Value("${mqtt.clientIdPrefix}")
    private String clientIdPrefix;

    @Value("${mqtt.topic}")
    private String topic;

    @Value("${mqtt.completionTimeout}")
    private int completionTimeout;

    @Value("${mqtt.connectionTimeout}")
    private int connectionTimeout;

    @Value("${mqtt.keepAliveInterval}")
    private int keepAliveInterval;

    @Value("${mqtt.qos}")
    private int qos;


    /**
     * mqtt客户端
     *
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        logger.info("连接参数初始化....");
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        //链接配置
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setUserName(username);
        connectOptions.setPassword(password.toCharArray());
        connectOptions.setServerURIs(new String[]{hostUrl});
        connectOptions.setKeepAliveInterval(keepAliveInterval);
        connectOptions.setConnectionTimeout(connectionTimeout);
        factory.setConnectionOptions(connectOptions);
        return factory;
    }

    /***
     * MQTT信息通道（消费者）
     * @return
     */
    @Bean(name = "mqttInputChannel")
    public MessageChannel mqttInputChannel() {
        logger.info("初始化接收消息通道....");
        return new DirectChannel();
    }

    /**
     * MQTT消息订阅绑定（消费者）MQTT消费者(JAVA Client端)和MQTT服务器保持长连接，
     * springboot服务启动完成之后可以在EMQ管理页面上看到只有消费者的clientId处于连接状态
     *
     * @return
     */
    @Bean
    public MessageProducer mqttInputBound() {
        String clientId = clientIdPrefix + "-consumer-" + System.currentTimeMillis();
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId, mqttClientFactory(), topic);
        adapter.setCompletionTimeout(completionTimeout);
        DefaultPahoMessageConverter converter = new DefaultPahoMessageConverter();
        converter.setPayloadAsBytes(true);
        adapter.setConverter(converter);
        adapter.setQos(qos);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    /***
     * MQTT信息通道（生产者）
     * @return
     */
    @Bean(name = "mqttOutputChannel")
    public MessageChannel mqttOutputChannel() {
        logger.info("初始化发送消息通道....");
        return new DirectChannel();
    }

    /**
     * MQTT消息处理器（生产者）MQTT消息生产者(JAVA Client)端，只有在往MQTT发布消息的时候才会连接MQTT服务器，
     * 这里有一个小坑，如果消息发布者和消息消费者使用相同的ClientId的话，每次发布消息都会报断开连接，因为消息消费者和消息生产者不能用相同的ClientId
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutputChannel")
    public MessageHandler mqttOutputBound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientIdPrefix + "-producer-" + System.currentTimeMillis(), mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(topic);
        return messageHandler;
    }
}
